package xyz.bali16.module.advise.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gitee.starblues.spring.MainApplicationContext;
import com.gitee.starblues.spring.SpringBeanFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import xyz.bali16.application.constant.ForumConstant;
import xyz.bali16.application.core.enums.ApiEnum;
import xyz.bali16.application.core.model.Result;
import xyz.bali16.application.core.model.UserVo;
import xyz.bali16.module.advise.utils.PageUtils;
import xyz.bali16.application.entity.User;
import xyz.bali16.application.service.UserService;
import xyz.bali16.module.advise.entity.Advise;
import xyz.bali16.module.advise.model.AdviseAddParam;
import xyz.bali16.module.advise.model.AdvisePageParam;
import xyz.bali16.module.advise.model.AdvisePageVo;
import xyz.bali16.module.advise.service.AdviseService;
import xyz.bali16.module.advise.utils.ResultUtils;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static xyz.bali16.application.core.model.Result.*;

/**
 * @author bali2 on 15/3/2023.
 * @version 1.0
 */
@RestController
@RequestMapping(BaseController.API + "advise")
@Api(tags = "留言接口")
@AllArgsConstructor
public class AdviseController {

    public static final Logger logger = LoggerFactory.getLogger(AdviseController.class);


    @Autowired
    private AdviseService adviseService;

    @Autowired
    private MainApplicationContext context;

    public PageUtils setAdvise(AdvisePageParam param) {
        //// 该用户的留言/回复总数
        //int adviseCounts = adviseService.getUserAdviseCount(userId);
        // 分页查询
        IPage<Advise> adviseIPage = adviseService.getPage(param);
        PageUtils advisePage = new PageUtils(adviseIPage);
        List<Advise> list = (List<Advise>) advisePage.getList();
        System.out.println("listA");
        System.out.println(list);
        // 封装留言和该留言对应的帖子信息
        advisePage.setTotalCount(list.size());
        List<Map<String, Object>> advises = new ArrayList<>();
        if (list != null) {
            // 获取符合条件的分页留言
            for (Advise advise : list) {
                Map<String, Object> map = new HashMap<>();

                // 获取子留言
                Wrapper<Advise> wrapper = Wrappers.<Advise>lambdaQuery().eq(Advise::getParentId,advise.getId());
                List<Advise> subAdvises = adviseService.list(wrapper);

                System.out.println("subAdvises");
                System.out.println(subAdvises);
                if (!CollectionUtils.isEmpty(subAdvises)) {
                    advise.setChildrens(subAdvises);
                    advise.setChildrenCount(subAdvises.size());
                }
                map.put("advise", advise);
                advises.add(map);
            }
        }
        advisePage.setList(advises);
        return advisePage;
    }

    @GetMapping
    //@PreAuthorize("@auth.permission('plugin:advise:query')")
    @ApiOperation("分页获取留言")
    public Result<AdvisePageVo> getAdvise(@Valid AdvisePageParam param) {
        try {
            AdvisePageVo advisePageVo = new AdvisePageVo();
            PageUtils advisePageUtils = setAdvise(param);
            advisePageVo.setPageUtils(advisePageUtils);
            advisePageVo.setAdviseCount(advisePageUtils.getTotalCount());
            return success(ApiEnum.GET_SUCCESS, advisePageVo);
        } catch (Exception e) {
            e.printStackTrace();
            //ResultUtils.errorLog(logger, e, "获取个人留言 '{}' 留言失败 {}", param.getUserId(), e.getMessage());
            return failure(ApiEnum.GET_ERROR, "获取个人留言失败", e);
        }
    }

    @PostMapping
    //@PreAuthorize("@auth.permission('plugin:advise:add')")
    public Result<String> addAdvise(@RequestBody @Valid AdviseAddParam param) {
        try {
            //SpringBeanFactory factory = context.getSpringBeanFactory();
            //UserService userService = factory.getBean(UserService.class);
            //User user = userService.getByUsername(AuthUtils.getCurrentUsername());
            adviseService.addAdvise(param);
            return success(ApiEnum.ADD_SUCCESS,"");
        } catch (Exception e) {
            e.printStackTrace();
            //ResultUtils.errorLog(logger, e, "添加留言留言 '{}' 失败. {}", param.getEntityId(), e.getMessage());
            return failure(ApiEnum.ADD_ERROR, e);
        }
    }

    @DeleteMapping("/{adviseId}")
    //@PreAuthorize("@auth.permission('plugin:advise:delete')")
    @ApiOperation("删除个人留言")
    @ApiImplicitParam(name = "userId", value = "个人留言id", paramType = "path", required = true)
    @Transactional
    public Result<String> deleteAdvise(@PathVariable("adviseId") String adviseId) {
        try {
            adviseService.delete(adviseId);
            return response(ApiEnum.DELETE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            ResultUtils.errorLog(logger, e, "删除个人留言 '{}' 失败. {}", adviseId, e.getMessage());
            return failure(ApiEnum.DELETE_ERROR, e);
        }
    }

}
